package com.blade.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 上传文件
 */
@Controller
@RequestMapping("upload")
public class CommonUpFile {
    @RequestMapping(method = RequestMethod.POST)
    public String addSpitterFromForm(@RequestParam(value="image", required=false) MultipartFile image) {
        try{
            if (!image.isEmpty()) {
                validateImage(image); // 校验图片

                // 保存图片
                saveImage("111111.jpg", image);
            }
        } catch (ImageUploadException e) {
            return "spitters/edit";
        }



        return "redirect:/books/";
    }

    private void  validateImage(MultipartFile image) {
        if (!image.getContentType().equals("image/jpeg")) {
            throw new ImageUploadException("Only JPG images accepted");
        }
    }

    private void saveImage(String filename, MultipartFile image) throws ImageUploadException {
        try{
            File file = new File("//Users/blade/Desktop/resources/" + filename);
            FileUtils.writeByteArrayToFile(file, image.getBytes());
        } catch (IOException e) {
            throw new ImageUploadException("Unable to save image", e);
        }
    }
}
